package com.ctsi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.core.common.util.$;
import com.ctsi.system.entity.UserRole;
import com.ctsi.system.mapper.UserRoleMapper;
import com.ctsi.system.service.IUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户角色表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
@AllArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

	@Override
	public IPage<UserRole> listPage(Page page, Search search) {
		LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
		return this.baseMapper.selectPage(page, queryWrapper);
	}

	@Override
	public List<Long> getUserRoleIdList(Long userId,Integer userType) {
		return this.list(Wrappers.<UserRole>query().lambda().eq(UserRole::getUserId, userId)
				.eq(UserRole::getType,userType))
				.stream().map(UserRole::getRoleId).collect(Collectors.toList());
	}

	@Override
	public boolean setRole(Long userId, List<Long> roleIds) {
		// 删除所拥有角色
		this.remove(Wrappers.<UserRole>query().lambda().eq(UserRole::getUserId, userId));
		// 授权角色
		roleIds.forEach(roleId ->{
			UserRole userRole = new UserRole();
			userRole.setRoleId(roleId);
			userRole.setUserId($.toLong(userId));
			this.save(userRole);
		});
		return Boolean.TRUE;
	}
}
